package com.junoppa.seckill.service;

import com.junoppa.seckill.dao.SeckillDao;
import com.junoppa.seckill.entity.Seckill;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * @author junoppa
 */
@Service
public class SeckillServiceImpl implements  SeckillService{

    @Autowired
    private SeckillDao seckillDao;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public int kill(int id) {
        int i = 0;
        Seckill seckill = seckillDao.findSeckillById(id);
        // 如果售空，则返回售空，如果没有则返回订单编号
        if (seckill.getTotal()==(seckill.getSale())) {
            return i ;
        } else {
            int res = seckillDao.updateSeckillAndVersionSaleById(seckill);
            if (res == 0) {
                return i ;
            }
            return 1 ;
        }
    }

    @Override
    public boolean allowVisit(String uid) {
        if (uid == null) {
            throw new RuntimeException("参数不合法，请重试~~~");
        }
        // 检查访问频次
        String freKey = "LIMIT_VISIT_" + uid;

        String freValue = stringRedisTemplate.opsForValue().get(freKey);

        // 用户没有访问或者上一轮访问限制到时
        if (freValue == null) {
            stringRedisTemplate.opsForValue().set(freKey,"1");
            return true;
        }else{
            return false;
        }

    }


}
